package cn.droidlover.xdroidmvp.view.picker.picker;

import android.app.Activity;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import cn.droidlover.xdroidmvp.view.picker.WheelView;

import static cn.droidlover.xdroidmvp.view.picker.popup.BottomPopup.WRAP_CONTENT;


/**
 * 地址选择器（包括省级、地级、县级）。
 * 地址数据见示例项目的“city.json”，来源于国家统计局官网（http://www.stats.gov.cn/tjsj/tjbz/xzqhdm）
 *
 * @author 李玉江[QQ:1032694760]
 * @since 2015/12/15
 */
public class AddressPicker extends LinkagePicker {
    private OnAddressPickListener onAddressPickListener;
    private boolean hideProvince = false;
    private boolean hideCounty = false;

    private ArrayList<Province> proviceLists = new ArrayList<>();
  //  protected ArrayList<City> cityLists = new ArrayList<City>();

    private ArrayList<String> proviceIds = new ArrayList<>();

    private Province province;

    private City city;

    private String proviceId;

    private String cityId;

    private String areaId;

    /**
     * Instantiates a new Address picker.
     *
     * @param activity the activity
     * @param data     the data
     */
    public AddressPicker(Activity activity, ArrayList<Province> data) {
        super(activity);
        int provinceSize = data.size();
        //添加省
        for (int x = 0; x < provinceSize; x++) {
            Province pro = data.get(x);
            firstList.add(pro.getProvince());

            proviceLists.add(pro);
            ArrayList<City> cities = pro.getCity();
            ArrayList<String> xCities = new ArrayList<>();
            ArrayList<ArrayList<String>> xCounties = new ArrayList<>();
            int citySize = cities.size();
            //添加地市
            for (int y = 0; y < citySize; y++) {
                City cit = cities.get(y);
                xCities.add(cit.getCity());
            //    cityLists.add(cit);

                ArrayList<Area> counties = cit.getArea();
                ArrayList<String> yCounties = new ArrayList<>();
                int countySize = counties.size();
                //添加区县
                if (countySize == 0) {
                    yCounties.add(cit.getCity());
                } else {
                    for (int z = 0; z < countySize; z++) {
                        Area area=  counties.get(z);
                        if(area !=null){
                            yCounties.add(area.getArea());


                        }
                    }
                }
                xCounties.add(yCounties);
            }
            secondList.add(xCities);

            thirdList.add(xCounties);
        }
    }

    /**
     * Sets selected item.
     *
     * @param province the province
     * @param city     the city
     * @param county   the county
     */
    @Override
    public void setSelectedItem(String province, String city, String county) {
        super.setSelectedItem(province, city, county);
    }

    /**
     * 隐藏省级行政区，只显示地市级和区县级。
     * 设置为true的话，地址数据中只需要某个省份的即可
     * 参见示例中的“city2.json”
     *
     * @param hideProvince the hide province
     */
    public void setHideProvince(boolean hideProvince) {
        this.hideProvince = hideProvince;
    }

    /**
     * 隐藏县级行政区，只显示省级和市级。
     * 设置为true的话，hideProvince将强制为false
     * 数据源依然使用“city.json” 仅在逻辑上隐藏县级选择框。
     *
     * @param hideCounty the hide county
     */
    public void setHideCounty(boolean hideCounty) {
        this.hideCounty = hideCounty;
    }

    /**
     * Sets on address pick listener.
     *
     * @param listener the listener
     */
    public void setOnAddressPickListener(OnAddressPickListener listener) {
        this.onAddressPickListener = listener;
    }

    @Deprecated
    @Override
    public void setOnLinkageListener(OnLinkageListener onLinkageListener) {
        throw new UnsupportedOperationException("Please use setOnAddressPickListener instead.");
    }

    @Override
    @NonNull
    protected View makeCenterView() {
        if (hideCounty) {
            hideProvince = false;
        }
        if (firstList.size() == 0) {
            throw new IllegalArgumentException("please initial data at first, can't be empty");
        }
        LinearLayout layout = new LinearLayout(activity);
        layout.setOrientation(LinearLayout.HORIZONTAL);
        layout.setGravity(Gravity.CENTER);
        final WheelView provinceView = new WheelView(activity);
        final int width = screenWidthPixels / 3;
        provinceView.setLayoutParams(new LinearLayout.LayoutParams(width, WRAP_CONTENT));
        provinceView.setTextSize(WheelView.TEXT_CITY_SIZE);
        provinceView.setTextColor(textColorNormal, textColorFocus);
        provinceView.setLineVisible(lineVisible);
        provinceView.setLineColor(lineColor);
        provinceView.setOffset(offset);
        layout.addView(provinceView);
        if (hideProvince) {
            provinceView.setVisibility(View.GONE);
        }
        final WheelView cityView = new WheelView(activity);
        cityView.setLayoutParams(new LinearLayout.LayoutParams(width, WRAP_CONTENT));
        cityView.setTextSize(WheelView.TEXT_CITY_SIZE);
        cityView.setTextColor(textColorNormal, textColorFocus);
        cityView.setLineVisible(lineVisible);
        cityView.setLineColor(lineColor);
        cityView.setOffset(offset);
        layout.addView(cityView);
        final WheelView countyView = new WheelView(activity);
        countyView.setLayoutParams(new LinearLayout.LayoutParams(width, WRAP_CONTENT));
        countyView.setTextSize(WheelView.TEXT_CITY_SIZE);
        countyView.setTextColor(textColorNormal, textColorFocus);
        countyView.setLineVisible(lineVisible);
        countyView.setLineColor(lineColor);
        countyView.setOffset(offset);
        layout.addView(countyView);
        if (hideCounty) {
            countyView.setVisibility(View.GONE);
        }
        provinceView.setItems(firstList, selectedFirstIndex);
        provinceView.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(boolean isUserScroll, int selectedIndex, String item) {
                selectedFirstText = item;
                selectedFirstIndex = selectedIndex;
                selectedThirdIndex = 0;
                if(proviceLists !=null && proviceLists.size() !=0){
                    //根据省份名称获取对应的id
                    if(proviceLists.get(selectedFirstIndex).getProvince().equals(selectedFirstText)){
                        province =proviceLists.get(selectedFirstIndex);
                        proviceId =  province.getProvince_id();
                  //      LogUtils.d("获取到的proviceId",proviceId);
                    }

                }

                //根据省份获取地市
                cityView.setItems(secondList.get(selectedFirstIndex), isUserScroll ? 0 : selectedSecondIndex);

                if(thirdList.get(selectedFirstIndex).size() !=0){
                    //根据地市获取区县
                    countyView.setItems(thirdList.get(selectedFirstIndex).get(0), isUserScroll ? 0 : selectedThirdIndex);
                }else{
                    countyView.setItems(proviceIds, isUserScroll ? 0 : selectedThirdIndex);
                }



            }
        });
        cityView.setItems(secondList.get(selectedFirstIndex), selectedSecondIndex);
        cityView.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(boolean isUserScroll, int selectedIndex, String item) {
                selectedSecondText = item;
                selectedSecondIndex = selectedIndex;


                if(province !=null){
                    List<City> cityLists = province.getCity();
                    if(cityLists !=null && cityLists.size() !=0){
                        //根据城市名称获取对应的id
                        //根据城市名称获取对应的id
                        for(int i = 0;i<cityLists.size();i++){
                         City   citys = cityLists.get(i);
                            if(citys.getCity().equals(selectedSecondText)){
                                cityId =  citys.getCity_id();
                                city = citys;
                            //    LogUtils.d("获取到的cityId",cityId);
                            }

                        }
                    }
                }


                if(thirdList.get(selectedFirstIndex).size() !=0){
                    //根据地市获取区县
                    countyView.setItems(thirdList.get(selectedFirstIndex).get(selectedSecondIndex), isUserScroll ? 0 : selectedThirdIndex);

                }


            }
        });
        countyView.setItems(thirdList.get(selectedFirstIndex).get(selectedSecondIndex), selectedThirdIndex);
        countyView.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(boolean isUserScroll, int selectedIndex, String item) {
                selectedThirdText = item;
                selectedThirdIndex = selectedIndex;

                        if(city !=null){
                            List<Area> areaLists = city.getArea();
                            if(areaLists !=null && areaLists.size() !=0){
                                //根据城市名称获取对应的id
                                for(int j = 0;j<areaLists.size();j++){
                                    Area area = areaLists.get(j);
                                    if(area.getArea().equals(selectedThirdText)){
                                        areaId =  area.getArea_id();
                                  //      LogUtils.d("获取到的areaId",areaId);
                                    }

                                }
                            }
                        }

            }
        });
        return layout;
    }

    @Override
    public void onSubmit() {
        if (onAddressPickListener != null) {
            if (hideCounty) {
                onAddressPickListener.onAddressPicked(selectedFirstText, selectedSecondText, null,proviceId, cityId, null);
            } else {
                onAddressPickListener.onAddressPicked(selectedFirstText, selectedSecondText, selectedThirdText,proviceId, cityId, areaId);
            }
        }
    }

    /**
     * The interface On address pick listener.
     */
    public interface OnAddressPickListener {

        /**
         * On address picked.
         *
         * @param province the province
         * @param city     the city
         * @param county   the county ，if {@hideCounty} is true，this is null
         */
        void onAddressPicked(String province, String city, String county, String provinceId, String cityId, String countyId);

    }

    /**
     * The type Area.
     */
    public static class Area {
        /**
         * The Area id.
         */
        String area_id;
        /**
         * The Area name.
         */
        String area;

        public String getArea_id() {
            return area_id;
        }

        public void setArea_id(String area_id) {
            this.area_id = area_id;
        }

        public String getArea() {
            return area;
        }

        public void setArea(String area) {
            this.area = area;
        }
    }

    /**
     * The type Province.
     */
    public static class Province implements Serializable {
        /**
         * The
         */
        String province_id;
        /**
         * The
         */
        String province;

        /**
         * The Cities.
         */
        ArrayList<City> city = new ArrayList<>();

        /**
         *
         *
         * @param
         */
        public void setCities(ArrayList<City> city) {
            this.city = city;
        }

        public String getProvince_id() {
            return province_id;
        }

        public void setProvince_id(String province_id) {
            this.province_id = province_id;
        }

        public String getProvince() {
            return province;
        }

        public void setProvince(String province) {
            this.province = province;
        }

        public ArrayList<City> getCity() {
            return city;
        }

        public void setCity(ArrayList<City> city) {
            this.city = city;
        }
    }

    /**
     * The type City.
     */
    public static class City  implements Serializable {
        private ArrayList<Area> area = new ArrayList<>();

        /**
         * The
         */
        String city_id;
        /**
         * The
         */
        String city;

        public ArrayList<Area> getArea() {
            return area;
        }

        public void setArea(ArrayList<Area> area) {
            this.area = area;
        }

        public String getCity_id() {
            return city_id;
        }

        public void setCity_id(String city_id) {
            this.city_id = city_id;
        }

        public String getCity() {
            return city;
        }

        public void setCity(String city) {
            this.city = city;
        }
    }


}
